<template>
    <div class="withdraw_record">
        <div class="withdraw_record_bottom">
            <!-- 查询 -->
            <div class="zw-form-layout">
                <el-form ref="formRef" :model="form" label-width="auto">
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="申请人信息" prop="applyUser">
                                <el-input
                                    v-model="form.applyUser"
                                    clearable
                                    placeholder="请输入申请人的昵称和手机号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="审核状态" prop="auditStatus">
                                <el-select v-model="form.auditStatus" placeholder="全部">
                                    <el-option
                                        v-for="item in auditStatusList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="提现至" prop="withdrawTo">
                                <el-select v-model="form.withdrawTo" placeholder="全部">
                                    <el-option
                                        v-for="item in withdrawToList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="申请时间" prop="createdAt">
                                <el-date-picker
                                    v-model="form.createdAt"
                                    type="datetimerange"
                                    range-separator="至"
                                    :default-time="defaultTime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="审核时间" prop="auditAt">
                                <el-date-picker
                                    v-model="form.auditAt"
                                    type="datetimerange"
                                    range-separator="至"
                                    :default-time="defaultTime"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" class="zw-form-btns">
                            <el-button type="primary" @click="searchHandler">查询</el-button>
                            <el-button plain @click="resetHandler">清空</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <!-- 列表 -->
            <el-table :data="tableList" :stripe="true">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template v-if="['bankInfo', 'operations', 'auditStatusName'].includes(prop)" #default="{ row }">
                        <template v-if="prop === 'auditStatusName'">
                            <div class="custom-status-line">
                                <span :class="`custom-status-${row.auditStatus}`">{{ row.auditStatusName }}</span>
                                <!-- todo:打款失败4原因和拒绝原因5 -->
                                <el-popover
                                    v-if="prop === 'auditStatusName' && [4, 5].includes(row.auditStatus)"
                                    placement="top"
                                    :width="300"
                                    trigger="hover"
                                    effect="dark"
                                    :content="row.auditStatus == 4 ? row.failedReason : row.rejectReason">
                                    <template #reference>
                                        <el-icon
                                            class="custom-status-line-status"
                                            v-if="prop === 'auditStatusName' && [4, 5].includes(row.auditStatus)"
                                            ><QuestionFilled
                                        /></el-icon>
                                    </template>
                                </el-popover>
                            </div>
                        </template>
                        <template v-if="prop === 'operations'">
                            <el-button
                                v-for="{ label, fn, ref, auth } in row.operations"
                                :key="label"
                                @click="fn(row, ref)"
                                size="small"
                                :ref="el => setItemRef(el, `${ref}${row.id}`)"
                                class="table-button"
                                v-auth="auth"
                                >{{ label }}</el-button
                            >
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </div>
        <!-- popover弹窗 -->
        <el-popover
            popper-class="custom-withdraw-popover-class"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            placement="top"
            trigger="click"
            virtual-triggering
            :width="240"
            :visible="popoverVisible">
            <!-- todo:不同的内容 -->
            <div
                class="custom-withdraw-popover-main"
                v-click-outside="onClickOutside"
                v-if="['againButtonRef'].includes(currentRow.ref)">
                <!-- 删除 -->
                <h3 style="margin-bottom: 16px" v-if="currentRow.ref == 'againButtonRef'">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>确定打款吗？
                </h3>
                <div style="text-align: right">
                    <el-button size="small" @click="popoverVisibleHandler()">取消</el-button>
                    <el-button size="small" type="primary" @click="popoverConfirmHandler()">确定</el-button>
                </div>
            </div>
        </el-popover>
        <AuditDialog ref="auditDialog" @confirm="queryListHandler"></AuditDialog>
        <InfoDialog ref="infoDialog"></InfoDialog>
    </div>
</template>

<script name="withdrawRecord" setup>
import { ref, unref, reactive, computed, onMounted, onUnmounted, onActivated, onDeactivated, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ClickOutside as vClickOutside } from 'element-plus';
import request from '@/request/index';
import constants from '@/commons/constants';
import { setLayout, resetLayout } from '@/hooks/layout';
import Pagination from '@/components/Pagination.vue';
import { format, cloneDeep, packSelectObjUtil } from '@/commons/utils.js';
import AuditDialog from './auditDialog.vue';
import InfoDialog from './infoDialog.vue';

const router = useRouter();
const withdrawToList = reactive(packSelectObjUtil(constants.WITHDRAW_TYPE));
const auditStatusList = reactive(packSelectObjUtil(constants.WITHDRAW_AUDIT_STATUS));

// todo:优化代码结构
const form = reactive({
    page: 1, //分页页码，数字类型
    perPage: 10, //默认每页10条
    applyUser: '', //申请人信息
    auditStatus: 0, //审核状态: 0-全部 1-待审核 2-打款中 3-打款成功 4-打款失败 5-已拒绝
    withdrawTo: 0, //提现至: 0-全部 1-微信 2-银行卡
    createdAt: [], //申请时间
    auditAt: [] //审核时间
});
let formClone = reactive(null);
const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)];
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);

const auditDialog = ref();
const infoDialog = ref();

// popover ref
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({ ref: null, id: null });

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '提现编号', prop: 'sn', showOverflowTooltip: true, minWidth: '150' },
        { label: '昵称', prop: 'nickName', minWidth: '120', showOverflowTooltip: true },
        { label: '姓名', prop: 'realName', minWidth: '120', showOverflowTooltip: true },
        { label: '手机号', prop: 'mobile', width: '120' },
        { label: '提现金额', prop: 'amount', minWidth: '120', showOverflowTooltip: true },
        { label: '提现至', prop: 'withdrawToName', width: '100' },
        { label: '银行卡信息', prop: 'bankInfo', showOverflowTooltip: true, width: '250' },
        { label: '审核状态', prop: 'auditStatusName', width: '150' },
        { label: '申请时间', prop: 'createdAt', width: '200' },
        { label: '审核时间', prop: 'auditAt', width: '200' },
        { label: '操作', prop: 'operations', width: '180', fixed: 'right' }
    ];
    return baseTableColumns;
});

// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryListHandler();
};
/**
 * 分页查询
 */
const queryListHandler = async () => {
    const _form = cloneDeep(form);
    _form.createdAtStart = _form.createdAt?.[0] ? format(_form.createdAt?.[0], 'YYYY-MM-DD HH:mm:ss') : null;
    _form.createdAtEnd = _form.createdAt?.[1] ? format(_form.createdAt?.[1], 'YYYY-MM-DD HH:mm:ss') : null;
    delete _form.createdAt;
    _form.auditAtStart = _form.auditAt?.[0] ? format(_form.auditAt?.[0], 'YYYY-MM-DD HH:mm:ss') : null;
    _form.auditAtEnd = _form.auditAt?.[1] ? format(_form.auditAt?.[1], 'YYYY-MM-DD HH:mm:ss') : null;
    delete _form.auditAt;
    const res = await request('withdrawList', _form);
    // const res = {
    //     data: {
    //         list: [
    //             {
    //                 id: 1001,

    //                 sn: 'A80652bF-8d1B-09Fb-Ec4d-89e7FBe8f4C8',

    //                 nickName: 'Paul Young',

    //                 realName: '毛艳',

    //                 mobile: '13911110000',

    //                 amount: 10000,

    //                 withdrawTo: 1,

    //                 withdrawToName: '微信',

    //                 bankName: '招商银行',

    //                 bankAccountNo: '393994943993493',

    //                 auditStatus: 4,

    //                 auditStatusName: 'sss',

    //                 failedReason: '失败原因',

    //                 rejectReason: '拒绝原因',

    //                 auditAt: '2023-01-01 11:43:25',

    //                 createdAt: '2023-01-01 12:43:25'
    //             }
    //         ]
    //     }
    // };
    const list = (res.data.list || []).map(item => {
        // todo: 根据不同状态显示不同按钮
        // todo:提现金额
        item.amount = '￥ ' + item.amount / 100;
        item.nickName = item.nickName || '-';
        item.sn = item.sn || '-';
        item.mobile = item.mobile || '-';
        item.realName = item.realName || '-';
        item.createdAt = item.createdAt || '-';
        item.auditAt = item.auditAt || '-';
        item.bankInfo = item.withdrawTo == 1 ? '-' : (item.bankName || '-') + ' ' + (item.bankAccountNo || '-');
        // todo:权限
        const btns = [
            { label: '审核', fn: auditHandler, ref: 'auditButtonRef', auth: 'withdraw_record:audit' },
            { label: '详情', fn: infoHandler, ref: 'infoButtonRef', auth: 'withdraw_record:info' },
            { label: '重新打款', fn: againHandler, ref: 'againButtonRef', auth: 'withdraw_record:audit' }
        ];
        if (item.auditStatus == 1) {
            item.operations = [btns[0]];
        } else if ([2, 3, 5].includes(item.auditStatus / 1)) {
            item.operations = [btns[1]];
        } else if (item.auditStatus == 4) {
            item.operations = [btns[1], btns[2]];
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
};
/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
    formClone = cloneDeep(form);
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryListHandler();
};
/** 按钮组操作 */
const popoverHandler = ({ id, auditStatus }, ref) => {
    buttonRef.value = itemRefs[`${ref}${id}`];
    currentRow.ref = ref;
    currentRow.id = id;
    currentRow.auditStatus = auditStatus;

    nextTick(() => {
        popoverVisible.value = true;
    });
};
// 审核
const auditHandler = row => {
    auditDialog?.value?.openDialog(row);
};
// 详情
const infoHandler = row => {
    infoDialog?.value?.openDialog(row);
};
// 重新打款
const againHandler = (row, ref) => {
    popoverHandler(row, ref);
};

// 点击popover外部
const onClickOutside = el => {
    popoverVisibleHandler();
};
// 控制popover展示隐藏
const popoverVisibleHandler = (visible = false) => {
    popoverVisible.value = visible;
};
// popover确定
const popoverConfirmHandler = async () => {
    // todo:重新打款
    await request('withdrawTransfer', { id: currentRow.id });
    popoverVisibleHandler();
    queryListHandler();
    ElMessage({
        type: 'success',
        message: '操作成功'
    });
};

const getAllData = () => {
    searchHandler();
};

onActivated(() => {
    Object.keys(formClone || {})?.forEach(key => {
        form[key] = formClone[key];
    });
    getAllData();
    setLayout();
});
onDeactivated(() => {
    resetLayout();
});
</script>
<style lang="scss">
.custom-withdraw-popover-class {
    padding: 0px !important;
    h3,
    p {
        margin: 0;
    }
    h3 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        display: flex;
        align-items: center;
        margin-bottom: 10px;
        .custom-icon {
            width: 14px;
            height: 14px;
            margin-right: 9px;
            color: #faad14;
            margin-top: 2px;
        }
    }

    p {
        padding-left: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        line-height: 16px;
        margin: 0 0 16px;
    }

    p + div {
        text-align: right;
    }

    .custom-preview {
        margin-top: 16px;
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
    }
}
.custom-withdraw-popover-main {
    padding: 16px;
}
</style>
<style lang="scss" scoped>
@import './style/index.scss';
</style>
